import os
import datetime
import shutil
import paramiko
import getpass
from GuidsSync import GuidsSync,GuidDescr

repoHost="vsys01775"
repoUser="guid"
repoPass="cghfdrf"
repoPath="/home/blokhin_sn/repo/guids"
ssh:paramiko.SSHClient = None
sftp:paramiko.SFTPClient = None
gs:GuidsSync = None

if __name__=="__main__":
    try:
        guids_path = os.path.dirname(os.path.realpath(__file__))+"\\guids"
        
        print("start copy guids to repo")
        ssh = paramiko.SSHClient()
        ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
        # passw = getpass.getpass(f"Пароль {repoUser}@{repoHost}:")
        ssh.connect(repoHost,username=repoUser,password=repoPass)
        print(f"{repoHost} connected")
        sftp = ssh.open_sftp()
        print("sftp opened")
        
        for dirname, subdirs, files in os.walk(guids_path):
            for filename in files:
                    itemName=os.path.join(dirname, filename)
                    stat =os.stat(itemName)
                    remote_path=f"{repoPath}/{filename}"
                    times = (stat.st_atime, stat.st_mtime)
                    sftp.put(itemName,remote_path)
                    sftp.utime(remote_path,times)
                    print(f"{remote_path} done") 
        
        # gs = GuidsSync(repoHost,repoUser,repoPass)
        # changed = gs.compare_files(repoPath,guids_path)
        # print("Измененные файлы на сервере:")
        # for file_guid  in  changed[0].keys():
        #     print(f"{file_guid} {changed[0][file_guid].name} -> {changed[0][file_guid].mtime_dt}")
        # print("Измененные локальные файлы:")            
        # for file_guid  in  changed[1].keys():
        #     print(f"{file_guid} {changed[1][file_guid].name} -> {changed[1][file_guid].mtime_dt}")            
        # flag1 = input("Отправить на сервер? [y/n]:")
        # if flag1=="y":
        #     print("start transfer")
        #     gs.send_to_remote()
        # flag2 = input("Получить файлы с сервера? [y/n]:")
        # if flag2=="y":
        #     print("start transfer")
        #     gs.get_from_remote()                   
                                       
    except Exception as exp:
        print(f"error: {exp}")
    
    finally:
        if sftp is not None: sftp.close()
        if ssh is not None: ssh.close()
        if gs is not None: gs.close_connection()
        print("disconnected")
        
        